<script setup>
import BindAccountButton from './BindAccountButton.vue'
import { ref, defineModel, inject } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import userApi from '@/apis/user'

const model = defineModel()
const authStore = useAuthStore()
const activeName = ref('info')
const rules = ref({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在2到20个字符之间', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
})
const reloadUserInfo = inject('reloadUserInfo')

const handleClick = (tab, event) => {
  console.log(tab, event)
}

const submitForm = async () => {
  const { data } = await userApi.profile.update(model.value)
  authStore.setUser(data)
  ElMessage.success('更新成功')
}
</script>
<template>
  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="个人信息" name="info">
      <div class="flex-1 mt-5 space-y-5">
        <el-form :model="model" label-width="auto" :rules="rules">
          <el-form-item label="账号">
            <span>{{ model.username }}</span>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="model.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="model.gender">
              <el-radio :value="0">保密</el-radio>
              <el-radio :value="1">男</el-radio>
              <el-radio :value="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" v-if="$attrs.bindEmail">
            <el-input v-model="model.email" placeholder="绑定邮箱地址" disabled>
              <template #append>
                <BindAccountButton
                  type="email"
                  :account="model.email"
                  :unbind="model.email.length > 0"
                  @success="reloadUserInfo"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile" v-if="$attrs.bindMobile">
            <el-input v-model="model.mobile" placeholder="绑定手机号" disabled>
              <template #append>
                <BindAccountButton
                  type="mobile"
                  :account="model.mobile"
                  :unbind="model.mobile.length > 0"
                  @success="reloadUserInfo"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="submitForm">
              <span class="pl-1">更新信息</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-tab-pane>
  </el-tabs>
</template>
